// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.superlists.servlet;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;

import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet for editing a single SuperList.
 *
 * @author sven@google.com (Sven Mawson)
 */
public class EditServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String action = req.getParameter("action");
    String body = CharStreams.toString(
        new InputStreamReader(req.getInputStream(), Charsets.UTF_8));
    if ("save".equals(action)) {
      SaveAction saveAction = new SaveAction(this, req, resp, body);
      saveAction.execute();
    } else if ("import".equals(action)) {
      ImportAction importAction = new ImportAction(this, req, resp, body);
      importAction.execute();
    } else if ("createList".equals(action)) {
      CreateListAction createAction = new CreateListAction(this, req, resp, body);
      createAction.execute();
    } else {
      throw new RuntimeException("Invalid action: " + action);
    }
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String id = req.getParameter("id");
    if (id == null) {
      // No id, redirect to home page.
      resp.sendRedirect("/");
      return;
    }

    LoadAction loadAction = new LoadAction(this, req, resp, id);
    loadAction.execute();

    // Dispatch to the JSP page.
    req.getRequestDispatcher("/list.jsp").forward(req, resp);
  }
}
